package com.sdy.healthcode.h5.controller;

import com.sdy.common.model.FileObj;
import com.sdy.common.model.Response;
import com.sdy.common.utils.Assert;
import com.sdy.healthcode.biz.constants.RedisConstants;
import com.sdy.mvc.controller.BaseController;
import com.sdy.mvc.service.FileService;
import com.sdy.redis.service.RedisService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/file")
@Api(tags = "文件接口")
public class FileController extends BaseController {
    @Autowired
    private FileService fileService;
    @Autowired
    private RedisService redisService;

    @PostMapping("/upload")
    @ApiOperation(value = "文件上传")
    @ApiImplicitParam(value = "上传类型", name = "type", required = true, allowableValues = "report,idcard")
    public Response upload(MultipartFile file, HttpServletRequest request, String type) throws Exception {
        Map<String, Object> result = new HashMap<>();
        Assert.isBlank(type, "缺少参数");
        FileObj fileObj = fileService.saveFile(file, "healthcode/" + type + "/" + getUserId(request));
        String fileName = file.getOriginalFilename();
        result.put("name", fileName);
        int t = fileName.lastIndexOf(".");
        String pureFileName = t > 0 ? fileName.substring(0, t) : fileName;
        result.put("pureName", pureFileName);
        result.put("url", fileObj.getPath());
        String uuid = UUID.randomUUID().toString();
        redisService.set(RedisConstants.FILE_UPLOAD_UUID + uuid, fileObj, 48 * 60 * 60);
        result.put("uuid", uuid);
        return Response.success(result);
    }
}
